
package com.laiketui.plugin.common.service;

import com.alibaba.fastjson.JSON;
import com.laiketui.core.cache.RedisUtil;
import com.laiketui.core.common.SplitUtils;
import com.laiketui.core.exception.LaiKeAPIException;
import com.laiketui.core.lktconst.GloabConst;
import com.laiketui.core.utils.tool.DataUtils;
import com.laiketui.core.utils.tool.DateUtil;
import com.laiketui.core.utils.tool.DoubleFormatUtil;
import com.laiketui.core.utils.tool.SerializePhpUtils;
import com.laiketui.plugin.common.config.Config;
import com.laiketui.plugin.common.domain.MainVo;
import com.laiketui.plugin.common.domain.base.*;
import com.laiketui.plugin.common.domain.base.config.PluginsModel;
import com.laiketui.plugin.common.domain.base.config.ProductConfigModel;
import com.laiketui.plugin.common.domain.base.config.plugin.*;
import com.laiketui.plugin.common.domain.base.coupon.CouponConfigModel;
import com.laiketui.plugin.common.domain.base.diy.DiyModel;
import com.laiketui.plugin.common.domain.base.goods.CartModel;
import com.laiketui.plugin.common.domain.base.group.GroupOrderConfigModel;
import com.laiketui.plugin.common.domain.base.log.AdminRecordModel;
import com.laiketui.plugin.common.domain.base.order.BuyAgainModal;
import com.laiketui.plugin.common.domain.base.order.CommentsImgModel;
import com.laiketui.plugin.common.domain.base.order.ReplyCommentsModel;
import com.laiketui.plugin.common.domain.base.payment.PaymentConfigModel;
import com.laiketui.plugin.common.domain.base.payment.PaymentModel;
import com.laiketui.plugin.common.domain.base.presell.PreSellConfigModel;
import com.laiketui.plugin.common.domain.base.seckill.SecondsConfigModel;
import com.laiketui.plugin.common.domain.base.seckill.SecondsProModel;
import com.laiketui.plugin.common.domain.lktconst.DictionaryConst;
import com.laiketui.plugin.common.domain.lktconst.ErrorCode;
import com.laiketui.plugin.common.domain.vo.SmsMessageModel;
import com.laiketui.plugin.common.domain.vo.UploadImagModel;
import com.laiketui.plugin.common.interfaces.PublicMchService;
import com.laiketui.plugin.common.interfaces.PublicMemberService;
import com.laiketui.plugin.common.interfaces.PubliceService;
import com.laiketui.plugin.common.mapper.*;
import com.laiketui.plugin.common.tool.ImgUploadUtils;
import com.laiketui.plugin.common.tool.Jssdk;
import com.laiketui.plugin.common.tool.MobileUtils;
import com.laiketui.plugin.common.tool.data.GoodsDataUtils;
import com.laiketui.plugin.common.tool.str.StringUtils;
import org.apache.commons.collections.MapUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.web.multipart.MultipartFile;
import tk.mybatis.mapper.entity.Example;

import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 公共服务
 *
 * @author Trick
 * @date 2020/10/15 17:07
 */
@Service
public class PublicServiceImpl implements PubliceService {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private FilesRecordModelMapper filesRecordModelMapper;

    @Autowired
    private UploadConfigModelMapper uploadConfigModelMapper;

    @Autowired
    private UserBaseMapper userBaseMapper;

    @Autowired
    private CustomerModelMapper customerModelMapper;

    @Autowired
    private MessageModelMapper messageModelMapper;

    @Autowired
    private MessageConfigModelMapper messageConfigModelMapper;

    @Autowired
    public StringRedisTemplate stringRedisTemplate;

    @Autowired
    private ProductListModelMapper productListModelMapper;

    @Autowired
    private ConfiGureModelMapper confiGureModelMapper;

    @Autowired
    private SecondsProModelMapper secondsProModelMapper;

    @Autowired
    private BuyAgainModalMapper buyAgainModalMapper;

    @Autowired
    private CartModelMapper cartModelMapper;

    @Autowired
    private MchModelMapper mchModelMapper;

    @Autowired
    private PublicMemberService publicMemberService;

    @Autowired
    private RedisUtil redisUtil;

    @Autowired
    private DictionaryNameModelMapper dictionaryNameModelMapper;

    @Autowired
    private GroupOrderConfigModelMapper groupOrderConfigModelMapper;


    @Override
    public String getImgPath(String imgName, Integer storeId) throws LaiKeAPIException {
        String imageUrl = "";
        try {
            if (storeId == null || StringUtils.isEmpty(imgName)) {
                return imageUrl;
            }
            //获取图片完整路径
            FilesRecordModel filesRecordModel = new FilesRecordModel();
            filesRecordModel.setStore_id(storeId + "");
            filesRecordModel.setImage_name(imgName);
            filesRecordModel = filesRecordModelMapper.getImageUrlOne(filesRecordModel);
            if (filesRecordModel != null) {
                //获取文件上传配置
                UploadConfigModel uploadConfigModel = new UploadConfigModel();
                uploadConfigModel.setUpserver(filesRecordModel.getUpload_mode());
                List<UploadConfigModel> uploadConfigModels = uploadConfigModelMapper.select(uploadConfigModel);
                //获取图片完整路径
                imageUrl = ImgUploadUtils.getImgPath(filesRecordModel, uploadConfigModels);
            }
        } catch (LaiKeAPIException l) {
            throw l;
        } catch (Exception e) {
            logger.error("获取图片路径失败! 异常", e);
            throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_TPLJHQSB, "图片路径获取失败", "getImgPath");
        }

        return imageUrl;
    }

    @Override
    public User getRedisUserCache(MainVo vo) throws LaiKeAPIException {
        try {
            User userCache = null;
            AdminModel adminModel;
            if (StringUtils.isEmpty(vo.getAccessId())) {
                throw new LaiKeAPIException(ErrorCode.BizErrorCode.LOGIN_INVALID, "请登录");
            }
            String h5Token = GloabConst.RedisHeaderKey.LOGIN_ACCESS_TOKEN;
            //获取当前登录用户数据
            Object cacheValue = redisUtil.get(h5Token + vo.getAccessId());
            if (cacheValue == null) {
                h5Token = GloabConst.RedisHeaderKey.LOGIN_ACCESS_MCH_TOKEN;
                cacheValue = redisUtil.get(h5Token + vo.getAccessId());
            }
            if (cacheValue == null) {
                h5Token = GloabConst.RedisHeaderKey.LOGIN_ACCESS_MANAGE_TOKEN;
                if (redisUtil.hasKey(h5Token + vo.getAccessId())) {
                    //转换登录
                    logger.info("后台登录插件,自动转换token登录");
                    //校验管理后台账号登录凭证
                    adminModel = getRedisAdminUserCache(vo.getAccessId(), redisUtil);
                    //如果是后台则自动登录商城自营店h5账号
                    Integer mchId = adminModel.getShop_id();
                    if (adminModel.getShop_id() == null || adminModel.getShop_id() == 0) {
                        //获取商城自营
                        mchId = customerModelMapper.getStoreMchId(vo.getStoreId());
                    }
                    userCache = userBaseMapper.mchLoginByUser(mchId);
                    if (userCache == null) {
                        throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_QTJZYD, "请添加自营店");
                    }
                    userCache.setAdminId(adminModel.getId());
                    //保存登录信息
                    redisUtil.set(userCache.getAccess_token(), JSON.toJSONString(userCache), GloabConst.LktConfig.LOGIN_EXISTENCE_TIME);
                    redisUtil.set(GloabConst.RedisHeaderKey.LOGIN_ACCESS_FLAG + userCache.getUser_id(), GloabConst.RedisHeaderKey.LOGIN_ACCESS_TOKEN + vo.getAccessId(), GloabConst.LktConfig.LOGIN_EXISTENCE_TIME);
                } else {
                    throw new LaiKeAPIException(ErrorCode.BizErrorCode.LOGIN_INVALID, "请重新登录");
                }
            }
            try {
                if (userCache == null) {
                    userCache = JSON.parseObject(cacheValue.toString(), User.class);
                }
                return userCache;
            } catch (Exception e) {
                e.printStackTrace();
                throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_WLFMQSHZS, "网络繁忙,请稍后再试", "getRedisUserCache");
            }
        } catch (LaiKeAPIException l) {
            throw l;
        } catch (Exception e) {
            logger.error("获取已经登陆的用户! 异常", e);
            throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_HQYHXXYC, "获取用户信息异常", "getRedisUserCache");
        }
    }

    @Override
    public List<Map<String, Object>> getGoodsActive(int storeId) throws LaiKeAPIException {
        try {
            return getGoodsActive(storeId, null);
        } catch (LaiKeAPIException l) {
            throw l;
        } catch (Exception e) {
            logger.error("获取商品支持的活动类型 异常:", e);
            throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_WLYC, "网络异常", "getGoodsActive");
        }
    }

    @Override
    public List<Map<String, Object>> getGoodsActive(int storeId, Integer active) throws LaiKeAPIException {
        List<Map<String, Object>> pluginArr = new ArrayList<>();
        try {
            //获取所有商品活动类型(插件)
            List<Map<String, Object>> goodsTagList = dictionaryNameModelMapper.getDicByName(DictionaryConst.DicName.DIC_GOODS_ACTIVE);
            for (Map<String, Object> goodsTagMap : goodsTagList) {
                Map<String, Object> dataMap = new HashMap<>(16);
                int value = StringUtils.stringParseInt(goodsTagMap.get("value"));
                //是否支持活动标识
                boolean isOpen = false;
                if (!"会员".equals(goodsTagMap.get("text"))) {
                    dataMap.put("name", goodsTagMap.get("text"));
                    dataMap.put("value", value);
                    if (DictionaryConst.GoodsActive.GOODSACTIVE_POSITIVE_PRICE.equals(value) || DictionaryConst.GoodsActive.GOODSACTIVE_VIP_DISCOUNT.equals(value)) {
                        //正价、会员特惠
                        isOpen = true;
                    } /*else if (DictionaryConst.GoodsActive.GOODSACTIVE_SECONDS.equals(value) && this.frontPlugin(storeId, DictionaryConst.Plugin.SECONDS, null)) {
                    //秒杀
                    isOpen = true;
                } else if (DictionaryConst.GoodsActive.GOODSACTIVE_INTEGRAL.equals(value) && this.frontPlugin(storeId, DictionaryConst.Plugin.INTEGRAL, null)) {
                    //积分
                    isOpen = true;
                } else if (DictionaryConst.GoodsActive.GOODSACTIVE_SUPPORT_PT.equals(value) && this.frontPlugin(storeId, DictionaryConst.Plugin.GOGROUP, null)) {
                    //拼团是否开启
                    isOpen = true;
                } else if (DictionaryConst.GoodsActive.GOODSACTIVE_POSITIVE_KJ.equals(value) && this.frontPlugin(storeId, DictionaryConst.Plugin.BARGAIN, null)) {
                    //砍价
                    isOpen = true;
                } else if (DictionaryConst.GoodsActive.GOODSACTIVE_POSITIVE_JP.equals(value) && this.frontPlugin(storeId, DictionaryConst.Plugin.AUCTION, null)) {
                    //竞拍
                    isOpen = true;
                } else if (DictionaryConst.GoodsActive.GOODSACTIVE_SECONDS.equals(value) && this.frontPlugin(storeId, DictionaryConst.Plugin.SECONDS, null)) {
                    //秒杀
                    isOpen = true;
                }*/
                    if (active != null) {
                        isOpen = isOpen && active.equals(value);
                    }
                    dataMap.put("status", isOpen);
                    pluginArr.add(dataMap);
                }

            }
            return pluginArr;
        } catch (LaiKeAPIException l) {
            throw l;
        } catch (Exception e) {
            logger.error("获取商品支持的活动类型 异常:", e);
            throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_WLYC, "网络异常", "getGoodsActive");
        }
    }

    /**
     * 获取后台用户信息
     *
     * @param accessId  -
     * @param redisUtil -
     * @return AdminModel
     * @throws LaiKeAPIException -
     * @author Trick
     * @date 2020/12/31 15:30
     */
    private AdminModel getRedisAdminUserCache(String accessId, RedisUtil redisUtil) throws LaiKeAPIException {
        //获取当前登录用户数据
        Object cacheValue = redisUtil.get(GloabConst.RedisHeaderKey.LOGIN_ACCESS_MANAGE_TOKEN + accessId);
        AdminModel userCache = null;
        if (cacheValue != null) {
            try {
                userCache = JSON.parseObject(cacheValue.toString(), AdminModel.class);
            } catch (Exception e) {
                e.printStackTrace();
                throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_WLFMQSHZS, "网络繁忙,请稍后再试", "getRedisUserCache");
            }
        } else {
            throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_QZXDL, "请重新登录");
        }

        return userCache;
    }

    @Override
    public boolean sendSms(int storeId, String phone, int type, int smsType, Map<String, String> smsParmaMap) throws LaiKeAPIException {
        try {
            StringBuilder redistKey = new StringBuilder();
            //模板名称
            String template;
            //验证码超时时间
            int outTime = 60;
            //注册验证码、通用模板 为五分钟
            if (GloabConst.VcodeCategory.REGISTER_CODE == smsType || GloabConst.VcodeCategory.CURRENCY_CODE == smsType) {
                outTime *= 5;
            }
            String header = this.getSmsHeade(smsType);

            //检查改手机号是否有发送给短信
            redistKey.append(header);
            redistKey.append(phone);
            if (redisUtil.hasKey(redistKey.toString()) && type == 0) {
                throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_CZPFQSHZS, "操作频繁,请稍后重试", "sendSms");
            }

            //验证短信模板是否存在
            MessageModel messageModel = new MessageModel();
            messageModel.setType1(smsType);
            messageModel.setStore_id(storeId);
            messageModel = messageModelMapper.selectOne(messageModel);
            if (messageModel == null || StringUtils.isEmpty(messageModel.getTemplateCode())) {
                logger.error("短信模板不存在,使用通用模板");
                messageModel = new MessageModel();
                messageModel.setType1(1);
                messageModel.setStore_id(storeId);
                messageModel = messageModelMapper.selectOne(messageModel);
                if (messageModel == null) {
                    logger.error("通用模板不存在");
                    throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_DXMBBCZ, "短信模板不存在", "sendSms");
                }
            }
            template = messageModel.getTemplateCode();
            //获取短信服务api密钥
            MessageConfigModel messageConfigModel = new MessageConfigModel();
            messageConfigModel.setStore_id(storeId);
            messageConfigModel = messageConfigModelMapper.selectOne(messageConfigModel);
            if (messageConfigModel != null) {

                if (type == GloabConst.VcodeCategory.TYPE_VERIFICATION) {
                    //生成x位验证码
                    String pcode = String.format("%06d", new Random().nextInt(999999));
                    smsParmaMap = new HashMap<>(16);
                    smsParmaMap.put("code", pcode);
                }

                //发送短信
                SmsMessageModel smsmodel = MobileUtils.sendSms(phone, template, messageModel.getSignName(), messageConfigModel.getAccessKeyId(), messageConfigModel.getAccessKeySecret(), smsParmaMap);
                String result = "OK";
                boolean flag = result.equals(smsmodel.getCode());
                //测试
                /*SmsMessageModel smsmodel = new SmsMessageModel();
                smsmodel.setMessage("测试");
                boolean flag = true;*/
                if (flag) {
                    if (type == GloabConst.VcodeCategory.TYPE_VERIFICATION) {
                        flag = redisUtil.set(redistKey.toString(), smsParmaMap.get("code"), outTime);
                        if (!flag) {
                            logger.error(smsParmaMap.get("code") + " 验证码保存失败");
                            throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_WLGZQSHZS, "网络故障,请稍后再试");
                        }
                    }
                } else {
                    logger.info("短信发送失败 参数:{},原因:{}", JSON.toJSONString(smsParmaMap), smsmodel.getMessage());
                    return false;
                }
                return true;
            } else {
                throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_PTWPZDXFW, "平台未配置短信服务", "sendSms");
            }
        } catch (LaiKeAPIException l) {
            throw l;
        } catch (Exception e) {
            logger.info("短信发送失败:", e);
            throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_WLYC, "网络异常", "sendSms");
        }
    }

    /**
     * 获取短信缓存头部
     *
     * @param smsType -
     * @return User
     * @throws LaiKeAPIException -
     * @author Trick
     * @date 2020/9/29 9:52
     */
    public String getSmsHeade(int smsType) throws LaiKeAPIException {
        try {
            String header = "";
            switch (smsType) {
                case GloabConst.VcodeCategory.LOGIN_CODE:
                    header = GloabConst.RedisHeaderKey.LOGIN_HEADER;
                    break;
                case GloabConst.VcodeCategory.REGISTER_CODE:
                    header = GloabConst.RedisHeaderKey.REGISTER_HEADER;
                    break;
                case GloabConst.VcodeCategory.UPDATE_PHOE_CODE:
                    //修改手机号
                    header = GloabConst.RedisHeaderKey.UPDATE_PHOE_CODE;
                    break;
                case GloabConst.VcodeCategory.UPDATE_PWD_CODE:
                    header = GloabConst.RedisHeaderKey.UPDATE_PASSWORDE;
                    break;
                case GloabConst.VcodeCategory.UPDATE_PWD_PAY_CODE:
                    header = GloabConst.RedisHeaderKey.UPDATE_PWD_PAY_CODE;
                    break;
                case GloabConst.VcodeCategory.DRAWING_CODE:
                    header = GloabConst.RedisHeaderKey.DRAWING_CODE;
                    break;
                case GloabConst.VcodeCategory.CURRENCY_CODE:
                case GloabConst.VcodeCategory.PAY_REFUND_ORDER:
                    header = GloabConst.RedisHeaderKey.CURRENCY_CODE;
                    break;
                default:
                    throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_DXLXCSBCZ, "短信类型参数不存在!", "sendSms");
            }
            return header;
        } catch (LaiKeAPIException l) {
            throw l;
        }
    }

    @Override
    public List<Map<String, Object>> productsList(List<Map<String, Object>> goodsInfoList, String cartIds, int buyType, String orderHead) throws LaiKeAPIException {
        Map<String, Object> resultMap = new HashMap<>(16);
        List<Map<String, Object>> ret = new ArrayList<>();
        try {
            if (StringUtils.isEmpty(cartIds)) {
                int pid = 0;
                int cid = 0;
                int num = 0;
                Integer secId = null;
                for (Map<String, Object> map : goodsInfoList) {
                    if (map.containsKey("pid")) {
                        pid = Integer.parseInt(map.get("pid").toString());
                    } else if (map.containsKey("cid")) {
                        cid = Integer.parseInt(map.get("cid").toString());
                    } else if (map.containsKey("num")) {
                        num = Integer.parseInt(map.get("num").toString());
                    } else if (map.containsKey("sec_id")) {
                        secId = Integer.parseInt(map.get("sec_id").toString());
                        resultMap.put("sec_id", secId);
                    }
                }
                //获取商品信息
                ProductListModel productListModel = new ProductListModel();
                productListModel.setId(pid);
                productListModel = productListModelMapper.selectOne(productListModel);
                //获取商品规格信息
                ConfiGureModel confiGureModel = new ConfiGureModel();
                confiGureModel.setId(cid);
                confiGureModel = confiGureModelMapper.selectOne(confiGureModel);
                if (productListModel != null) {
                    //判断商品是否上架
                    if (DictionaryConst.GoodsStatus.NOT_GROUNDING.equals((Integer.parseInt(productListModel.getStatus())))) {
                        throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_SPWSJ, "商品未上架", "productsList");
                    }
                    //砍价订单不需要判断库存,因为在砍价的时候就吧库存扣除了
                    if (!DictionaryConst.OrdersType.ORDERS_HEADER_KJ.equals(orderHead)) {
                        int stockNum;
                        //判断库存是否充足
                        if (DictionaryConst.OrdersType.ORDERS_HEADER_MS.equals(orderHead) && secId != null) {
                            //获取秒杀商品库存
                            SecondsProModel secondsProModel = new SecondsProModel();
                            secondsProModel.setActivity_id(secId);
                            secondsProModel.setAttr_id(cid);
                            secondsProModel = secondsProModelMapper.selectOne(secondsProModel);
                            if (secondsProModel != null) {
                                stockNum = secondsProModel.getNum();
                            } else {
                                throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_SPWKCXX, "商品无库存信息", "productsList");
                            }
                        } /*else if (DictionaryConst.OrdersType.PTHD_ORDER_PP.equals(orderHead) && secId != null) {
                            //获取秒杀商品库存
                            PtSecondsProModel secondsProModel = ptSecondsProModelMapper.selectByPrimaryKey(secId);
                            if (secondsProModel != null) {
                                stockNum = secondsProModel.getNum();
                            } else {
                                throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_SPWKCXX, "商品无库存信息", "productsList");
                            }
                        }*/ else {
                            if (confiGureModel != null) {
                                stockNum = confiGureModel.getNum();
                            } else {
                                throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_SPWKCXX, "商品无库存信息", "productsList");
                            }
                        }
                        if (stockNum < num) {
                            throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_KCBZ, "库存不足", "productsList");
                        }
                    }

                    resultMap.put("pid", pid);
                    resultMap.put("cid", cid);
                    resultMap.put("num", num);
                    ret.add(resultMap);
                } else {
                    throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_SPBCZ, "商品不存在", "productsList");
                }
            } else {
                //购物车数据不为空
                String[] cartIdsArray = cartIds.split(SplitUtils.DH);
                for (String cartId : cartIdsArray) {
                    if (buyType != 0) {
                        Example example = new Example(BuyAgainModal.class);
                        Example.Criteria criteria = example.createCriteria();
                        criteria.andGreaterThan("goods_num", 0);
                        criteria.andEqualTo("id", cartId);
                        List<BuyAgainModal> buyAgainModalList = buyAgainModalMapper.selectByExample(example);
                        for (BuyAgainModal buyAgainModal : buyAgainModalList) {
                            resultMap = new HashMap<>(16);
                            resultMap.put("pid", buyAgainModal.getGoods_id());
                            resultMap.put("num", buyAgainModal.getGoods_num());
                            resultMap.put("cid", buyAgainModal.getSize_id());
                            ret.add(resultMap);
                        }
                    } else {
                        Example example = new Example(CartModel.class);
                        Example.Criteria criteria = example.createCriteria();
                        criteria.andGreaterThan("goods_num", 0);
                        criteria.andEqualTo("id", cartId);
                        List<CartModel> cartModels = cartModelMapper.selectByExample(example);
                        for (CartModel cartModel : cartModels) {
                            resultMap = new HashMap<>(16);
                            resultMap.put("pid", cartModel.getGoods_id());
                            resultMap.put("num", cartModel.getGoods_num());
                            resultMap.put("cid", cartModel.getSize_id());
                            ret.add(resultMap);
                        }
                    }
                }
            }

        } catch (ClassCastException c) {
            throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_CSLXBZQ, "参数类型不正确", "productsList");
        } catch (LaiKeAPIException l) {
            throw l;
        } catch (Exception e) {
            logger.error("处理立即购买异常", e);
            throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_WLYC, "网络异常", "productsList");
        }
        return ret;
    }


    @Override
    public Map<String, Object> settlementProductsInfo(List<Map<String, Object>> products, int storeId, String productType) {
        //商品信息
        Map<String, Object> resutlProducts = new HashMap<>();
        try {
            //商品总价
            BigDecimal orderProductTotal = new BigDecimal(0);
            if (CollectionUtils.isEmpty(products)) {
                throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_CSBZQ, "参数不正确", "settlementProductsInfo");
            }
            //店铺商品信息
            Map<String, List<Map<String, Object>>> mchProductsResult = new HashMap<>();
            //店铺运费处理 products_freight
            Map<String, List<Map<String, Object>>> mchReightResult = new HashMap<>();
            for (Map<String, Object> map : products) {
                map.put("store_id", storeId);
                Map<String, Object> tmpRet = new HashMap<>(16);
                //是否免运费
                boolean isFreeFreight = false;
                if (DictionaryConst.OrdersType.ORDERS_HEADER_MS.equals(productType) || DictionaryConst.OrdersType.PTHD_ORDER_PM.equals(productType)) {
                    //秒杀商品信息
                    int secId = Integer.parseInt(map.get("sec_id").toString());
                    int needNum = Integer.parseInt(map.get("num").toString());
                    if (DictionaryConst.OrdersType.ORDERS_HEADER_MS.equals(productType)) {
                        tmpRet = secondsProModelMapper.settlementProductsInfo(storeId, needNum, secId, MapUtils.getIntValue(map, "cid"));
                    } else {
                        //平台暂时无用 2021-10-29 17:32:40
//                        tmpRet = ptSecondsProModelMapper.settlementProductsInfo(storeId, needNum, secId);
                    }
                    if ("1".equals(tmpRet.get("free_freight"))) {
                        isFreeFreight = true;
                    }
                } else {
                    tmpRet = productListModelMapper.settlementProductsInfo(map);
                }
                if (!CollectionUtils.isEmpty(tmpRet)) {
                    //商品信息
                    tmpRet.putAll(map);
                    // 产品单价 变成分
                    BigDecimal productPrice = new BigDecimal(String.valueOf(tmpRet.get("price")));
                    //如果是秒杀,则获取秒杀价格
                    if (DictionaryConst.OrdersType.ORDERS_HEADER_MS.equals(productType)) {
                        int type = MapUtils.getIntValue(tmpRet, "price_type");
                        //规格价格
                        BigDecimal attrPrice = new BigDecimal(MapUtils.getString(tmpRet, "attrPrice"));
                        if (type == 0) {
                            //百分比
                            productPrice = attrPrice.multiply(productPrice).divide(new BigDecimal("100"), 2, BigDecimal.ROUND_HALF_UP);
                        }
                    }


                    BigDecimal num = new BigDecimal(String.valueOf(map.get("num")));
                    int pid = Integer.parseInt(String.valueOf(map.get("pid")));
                    String weight = String.valueOf(tmpRet.get("weight"));
                    BigDecimal delta = productPrice.multiply(num);
                    orderProductTotal = orderProductTotal.add(delta);
                    //规格处理
                    String key = "attribute";
                    String attrs = (String) tmpRet.get(key);
                    String sku = GoodsDataUtils.getProductSkuValue(attrs);
                    tmpRet.put("size", sku);
                    tmpRet.remove(key);
                    //图片处理
                    key = "img";
                    String imgPath = getImgPath((String) tmpRet.get(key), storeId);
                    tmpRet.put(key, imgPath);

                    //运费处理
                    if (!isFreeFreight) {
                        //店铺id
                        String mch_key = String.valueOf(tmpRet.get("mch_id"));
                        //运费id
                        String fidStr = MapUtils.getString(tmpRet, "freight", "");
                        BigDecimal freight;

                        //店铺商品运费处理
                        Map<String, Object> freightInfo = new HashMap<>();
                        freightInfo.put("num", num);
                        freightInfo.put("pid", pid);
                        if (!org.apache.commons.lang3.StringUtils.isEmpty(fidStr)) {
                            freight = new BigDecimal(fidStr);
                            freightInfo.put("freight_id", freight);
                        }
                        freightInfo.put("weight", weight);

                        if (mchReightResult.containsKey(mch_key)) {
                            mchReightResult.get(mch_key).add(freightInfo);
                        } else {
                            List<Map<String, Object>> mchProductInfo = new ArrayList<>();
                            mchProductInfo.add(freightInfo);
                            mchReightResult.put(mch_key, mchProductInfo);
                        }

                        //按照店铺分类存储商品信息
                        if (mchProductsResult.containsKey(mch_key)) {
                            mchProductsResult.get(mch_key).add(tmpRet);
                        } else {
                            List<Map<String, Object>> mchProductInfo = new ArrayList<>();
                            mchProductInfo.add(tmpRet);
                            mchProductsResult.put(mch_key, mchProductInfo);
                        }
                    }

                }
            }

            //所有店铺id集合
            Set<String> mchids = mchProductsResult.keySet();
            //多店铺信息和商品信息集合
            List<Map<String, Object>> returnMchInfoAndProducts = new ArrayList<>();
            //店铺信息和店铺对应的商品信息已经店铺商品总价

            //结算界面按店铺结算的基本信息
            for (String mchid : mchids) {
                Map<String, Object> mchInfoAndProducts = new HashMap<>();
                //该店铺的商品
                List<Map<String, Object>> thisMchProducts = mchProductsResult.get(mchid);
                //商品信息
                mchInfoAndProducts.put("list", thisMchProducts);
                //店铺信息
                MchModel mchModel = new MchModel();
                mchModel.setId(Integer.parseInt(mchid));
                mchModel = mchModelMapper.selectOne(mchModel);
                mchInfoAndProducts.put("shop_id", mchModel.getId());
                mchInfoAndProducts.put("shop_name", mchModel.getName());
                mchInfoAndProducts.put("shop_logo", mchModel.getLogo());
                //店铺商品总价
                AtomicInteger mchProductTotal = new AtomicInteger(0);
                for (Map<String, Object> product : thisMchProducts) {
                    int productPrice = BigDecimal.valueOf(Double.parseDouble(String.valueOf(product.get("price"))) * 100).intValue();
                    int num = Integer.parseInt(String.valueOf(product.get("num")));
                    int delta = productPrice * num;
                    mchProductTotal = new AtomicInteger(mchProductTotal.addAndGet(delta));
                }
                mchInfoAndProducts.put("product_total", mchProductTotal.doubleValue() / 100.0);
                returnMchInfoAndProducts.add(mchInfoAndProducts);
            }

            //订单商品总额
            resutlProducts.put("products_total", orderProductTotal);
            //按店铺区分的商品信息
            resutlProducts.put("products", returnMchInfoAndProducts);
            //按店铺分类的商品运费信息
            resutlProducts.put("products_freight", mchReightResult);

            //TODO 以下这两个key没有使用到 ，php中使用的是第一个商品的信息
            resutlProducts.put("product_class", "==");
            resutlProducts.put("product_id", "111");

            return resutlProducts;
        } catch (Exception e) {
            e.printStackTrace();
            throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_HQDDQRXXSB, "获取订单确认信息失败", "settlementProductsInfo");
        }
    }


    @Override
    public Map<String, Object> getMemberPrice(List<Map<String, Object>> params, String userId, int storeId) throws LaiKeAPIException {
        try {
            if (CollectionUtils.isEmpty(params)) {
                throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_CSYC, "参数异常", "getMemberPrice");
            }
            //默认没有折扣
            BigDecimal gradeRate = new BigDecimal("1");
            ProductListModel productListModel = new ProductListModel();
            int pid = (Integer) ((List<Map<String, Object>>) (params.get(0).get("list"))).get(0).get("pid");
            productListModel.setId(pid);
            productListModel = productListModelMapper.selectOne(productListModel);
            String productType = DictionaryConst.OrdersType.ORDERS_HEADER_GM;
            String activeStr = productListModel.getActive();
            //特惠商品
            if ("6".equals(activeStr)) {
                productType = DictionaryConst.OrdersType.ORDERS_HEADER_TH;
            }
            gradeRate = new BigDecimal(String.valueOf(publicMemberService.getMemberGradeRate(productType, userId, storeId)));
            //订单产品总价
            BigDecimal orderProductTotal = new BigDecimal(0);
            //按照店铺计算
            for (Map<String, Object> mchAllInfo : params) {
                //店铺商品信息
                List<Map<String, Object>> mchProductsInfo = (List<Map<String, Object>>) mchAllInfo.get("list");
                if (CollectionUtils.isEmpty(mchProductsInfo)) {
                    throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_CSYC, "参数异常", "getMemberPrice");
                }
                //店铺商品总价
                BigDecimal mchSellProductTotal = new BigDecimal(0);
                //会员商品总价
                BigDecimal mchMemberProductTotal = new BigDecimal(0);
                for (Map<String, Object> productInfo : mchProductsInfo) {
                    //产品原始售价
                    BigDecimal productPrice = BigDecimal.valueOf(Double.valueOf(String.valueOf(productInfo.get("price"))));
                    //产品数量
                    BigDecimal num = new BigDecimal(String.valueOf(productInfo.get("num")));
                    //会员价
                    BigDecimal memberPrice = productPrice.multiply(gradeRate);
                    //设置会员价
                    productInfo.put("membership_price", memberPrice);
                    //会员单个产品总价
                    BigDecimal memberTotalPrice = memberPrice.multiply(num);
                    //售价总价
                    BigDecimal delta = productPrice.multiply(num);
                    //单个产品售价总价
                    mchSellProductTotal = mchSellProductTotal.add(delta);
                    //单个产品会员价总价
                    mchMemberProductTotal = mchMemberProductTotal.add(memberTotalPrice);
                    // 优惠后金额 如果没有优惠则原价
                    productInfo.put("amount_after_discount", memberTotalPrice);
                    //订单所有产品总价
                    orderProductTotal = orderProductTotal.add(memberTotalPrice);
                }
                //会员优惠价格
                mchAllInfo.put("grade_rate_amount", DoubleFormatUtil.format((mchSellProductTotal.subtract(mchMemberProductTotal)).doubleValue()));
                //店铺总产品价格
                mchAllInfo.put("product_total", DoubleFormatUtil.format(mchMemberProductTotal.doubleValue()));
            }

            Map<String, Object> result = new HashMap<>();
            //会员优惠
            result.put("grade_rate", gradeRate);
            result.put("products", params);
            //订单商品总价
            result.put("products_total", DoubleFormatUtil.format(orderProductTotal.doubleValue()));
            return result;
        } catch (Exception e) {
            e.printStackTrace();
            throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_HYYHJSSB, "会员优惠计算失败", "getMemberPrice");
        }

    }

    @Autowired
    private Config config;

    @Override
    public List<String> uploadImage(List<MultipartFile> multipartFiles, String uploadType, int storeType, int storeId) throws LaiKeAPIException {
        try {
            //默认使用oos
            if (StringUtils.isEmpty(uploadType)) {
                uploadType = GloabConst.UploadConfigConst.IMG_UPLOAD_OSS;
            }
            return uploadImage(multipartFiles, uploadType, storeType, storeId, null);
        } catch (LaiKeAPIException l) {
            throw l;
        } catch (Exception e) {
            logger.error("获取图片路径失败!", e);
            throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_TPLJHQSB, "图片路径获取失败", "getImgPath");
        }
    }

    @Override
    public List<String> uploadImage(List<MultipartFile> multipartFiles, String uploadType, int storeType, int storeId, Integer mchId) throws LaiKeAPIException {
        List<String> imgUrls;
        try {
            UploadImagModel imagModel = new UploadImagModel();
            imagModel.setUploadType(uploadType);
            //从数据库获取上传配置key
            UploadConfigModel uploadConfigModel = new UploadConfigModel();
            uploadConfigModel.setUpserver(imagModel.getUploadType() + "");
            List<UploadConfigModel> uploadConfigs = uploadConfigModelMapper.select(uploadConfigModel);

            //装载参数
            imagModel.setUploadConfigs(uploadConfigs);
            imagModel.setMultipartFiles(multipartFiles);
            //如果是本地则获取配置信息里的路径
            if (uploadType.equals(GloabConst.UploadConfigConst.IMG_UPLOAD_LOCALHOST1)) {
                imagModel.setUploadPath(config.getUploadPath());
            }
            //图片上传
            ImgUploadUtils imgupload = new ImgUploadUtils();
            imgUrls = imgupload.imgUpload(imagModel, storeId, storeType);

            if (imgUrls != null && imgUrls.size() > 0) {
                //添加上传记录信息
                for (String imgUrl : imgUrls) {
                    FilesRecordModel filesRecordModel = new FilesRecordModel();
                    filesRecordModel.setImage_name(ImgUploadUtils.getUrlImgByName(imgUrl, true));
                    filesRecordModel.setStore_id(storeId + "");
                    filesRecordModel.setStore_type(storeType + "");
                    filesRecordModel.setGroup("-1");
                    filesRecordModel.setUpload_mode(GloabConst.UploadConfigConst.IMG_UPLOAD_OSS);
                    if (mchId != null) {
                        filesRecordModel.setMch_id(mchId);
                    }
                    filesRecordModel.setAdd_time(new Date());
                    int count = filesRecordModelMapper.insertSelective(filesRecordModel);
                    if (count < 1) {
                        logger.info("图片上传失败,图片记录失败 参数：" + JSON.toJSONString(filesRecordModel));
                        throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_WLYC, "网络异常", "uploadImage");
                    }
                }
                return imgUrls;
            } else {
                throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_TPSCSB, "图片上传失败", "uploadImage");
            }
        } catch (LaiKeAPIException l) {
            throw l;
        } catch (Exception e) {
            logger.error("上传图片异常! ", e);
            throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_TPSCSB, "图片上传失败", "uploadImage");
        }
    }

    @Override
    public Map<String, Object> getCommentsDetailInfoById(Map<String, Object> parmaMap) throws LaiKeAPIException {
        Map<String, Object> resultMap = new HashMap<>(16);
        try {
            int total = replyCommentsModelMapper.countDynamic(parmaMap);
            List<Map<String, Object>> list = new ArrayList<>();
            if (total > 0) {
                list = replyCommentsModelMapper.selectDynamic(parmaMap);
                list.forEach(map -> {
                    map.put("id", MapUtils.getIntValue(map, "id"));
                    map.put("add_time", DateUtil.dateFormate(MapUtils.getString(map, "add_time"), GloabConst.TimePattern.YMDHMS));
                });
            }

            resultMap.put("total", total);
            resultMap.put("list", list);
        } catch (LaiKeAPIException l) {
            throw l;
        } catch (Exception e) {
            logger.error("获取商品回复明细 异常", e);
            throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_WLYC, "网络异常", "getCommentsDetailInfoById");
        }
        return resultMap;
    }

    @Override
    public List<Map<String, Object>> getGoodsCommentList(Map<String, Object> parmaMap) throws LaiKeAPIException {
        List<Map<String, Object>> resultList;
        try {
            int storeId = MapUtils.getInteger(parmaMap, "store_id");

            resultList = commentsModelMapper.getCommentsUserDynamicByPid(parmaMap);
            for (Map<String, Object> map : resultList) {
                int id = Integer.parseInt(map.get("id") + "");
                int attributeId = Integer.parseInt(map.get("attribute_id") + "");
                int anonymous = Integer.parseInt(map.get("anonymous") + "");
                //商品店铺id
                int goodsMchId = MapUtils.getInteger(map, "mch_id");
                //评论id
                int commentId = MapUtils.getIntValue(map, "id");
                //用户头像
                String headimgurl = map.get("headimgurl") + "";
                //评论时间
                String addTime = DateUtil.dateFormate(map.get("add_time").toString(), GloabConst.TimePattern.YMDHMS);
                //追平时间
                String reviewTime = "";
                if (map.containsKey("review_time")) {
                    reviewTime = DateUtil.dateFormate(map.get("review_time").toString(), GloabConst.TimePattern.YMDHMS);
                }
                //时间处理
                String time = addTime.substring(0, 10);
                //评论图片
                List<Map<String, String>> imgUrls = new ArrayList<>();
                //追平图片
                List<Map<String, String>> reviewImages = new ArrayList<>();
                //回复
                String replyAdmin = "";

                //统计图片数量
                CommentsImgModel commentsImgModel = new CommentsImgModel();
                commentsImgModel.setComments_id(id);
                List<CommentsImgModel> commentsImgModelList = commentsImgModelMapper.select(commentsImgModel);
                if (commentsImgModelList != null) {
                    for (CommentsImgModel commentsImg : commentsImgModelList) {
                        Map<String, String> commentMap = new HashMap<>(16);
                        //获取图片路径
                        String imgUrl = getImgPath(commentsImg.getComments_url(), storeId);
                        commentMap.put("url", imgUrl);
                        if (commentsImg.getType() == 0) {
                            //评论图片
                            imgUrls.add(commentMap);
                        } else {
                            //追评
                            reviewImages.add(commentMap);
                        }
                    }
                }
                //获取商品属性
                ConfiGureModel confiGureModel = new ConfiGureModel();
                confiGureModel.setId(attributeId);
                confiGureModel = confiGureModelMapper.selectOne(confiGureModel);
                //属性处理
                Map<String, String> attributeMap = DataUtils.cast(SerializePhpUtils.getUnserializeObj(confiGureModel.getAttribute(), Map.class));
                if (attributeMap == null) {
                    throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_SJCW, "数据错误");
                }
                StringBuilder attribute = new StringBuilder("");
                for (String key : attributeMap.keySet()) {
                    String attribyteKey = key;
                    String attribyteValue = attributeMap.get(key) + "";

                    int index = key.indexOf("_LKT_");
                    if (index > 0) {
                        attribyteKey = key.substring(0, attribyteKey.indexOf("_LKT"));
                        //属性值
                        attribyteValue = attribyteValue.substring(0, attribyteValue.indexOf("_LKT_"));
                    }
                    attribute.append(attribyteKey);
                    attribute.append(":");
                    attribute.append(attribyteValue);
                    attribute.append(",");
                }
                String attributeString = attribute.substring(0, attribute.lastIndexOf(","));

                //是否匿名处理
                if (anonymous == 1) {
                    map.put("user_name", "匿名");
                } else {
                    String userName = "匿名";
                    if (map.containsKey("user_name")) {
                        userName = map.get("user_name") + "";
                    }
                    map.put("user_name", userName);
                }
                //查询该条评论的回复
                replyAdmin = replyCommentsModelMapper.getMchReplyInfo(commentId, goodsMchId);
                if (StringUtils.isEmpty(replyAdmin)) {
                    replyAdmin = "";
                }

                map.put("time", time);
                map.put("add_time", addTime);
                map.put("review_time", reviewTime);
                map.put("headimgurl", headimgurl);
                map.put("images", imgUrls);
                map.put("review_images", reviewImages);
                map.put("attribute_str", attributeString);
                map.put("replyAdmin", replyAdmin);
            }
        } catch (ClassCastException c) {
            throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_CSLXBZQ, "参数类型不正确", "getGoodsCommentList");
        } catch (LaiKeAPIException l) {
            throw l;
        } catch (Exception e) {
            logger.error("获取商品评论信息异常", e);
            throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_WLYC, "网络异常", "getGoodsCommentList");
        }
        return resultList;
    }

    @Override
    public void delCommentsDetailInfoById(MainVo vo, int cid) throws LaiKeAPIException {
        try {
            ReplyCommentsModel replyCommentsOld = replyCommentsModelMapper.selectByPrimaryKey(cid);
            if (replyCommentsOld == null) {
                throw new LaiKeAPIException(ErrorCode.BizErrorCode.DATA_NOT_EXIST, "数据不存在");
            }
            replyCommentsModelMapper.deleteByPrimaryKey(cid);
        } catch (LaiKeAPIException l) {
            throw l;
        } catch (Exception e) {
            logger.error("获取商品评论信息异常", e);
            throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_WLYC, "网络异常", "getGoodsCommentList");
        }
    }

    @Override
    public boolean jurisdiction(int storeId, AdminModel admin, String url) throws LaiKeAPIException {
        try {
            if (admin != null && admin.getType() != 1) {
                int count = roleMenuModelMapper.countButtonRole(admin.getRole(), url);
                if (count > 0) {
                    return true;
                }
            }
        } catch (LaiKeAPIException l) {
            throw l;
        } catch (Exception e) {
            logger.error("获取后台权限按钮 异常", e);
            throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_WLYC, "网络异常", "jurisdiction");
        }

        return false;
    }

    @Autowired
    private PublicMchService publicMchService;

    @Autowired
    private DiyModelMapper diyModelMapper;

    @Override
    public boolean frontPlugin(int storeId, Integer mchId, String pluginCode, Map<String, Integer> pluginMap) throws LaiKeAPIException {
        try {
            PluginsModel pluginsModel = pluginsModelMapper.getPluginInfo2(pluginCode, storeId);
            if (DictionaryConst.Plugin.PLATFORMACTIVITIES.equals(pluginCode)) {
                if (pluginsModel != null) {
                    return true;
                }
                return true;
            }
            int status = 0;
            Integer zyMchId = 0;
            if (pluginsModel != null) {
                Integer mchIdTemp = mchId;
                if (mchId == null) {
                    mchId = customerModelMapper.getStoreMchId(storeId);
                }
                switch (pluginCode.toLowerCase()) {
                    case DictionaryConst.Plugin.SIGN:
                        //验证签到是否开启
                        SignConfigModel signConfigModel = new SignConfigModel();
                        signConfigModel.setStore_id(storeId);
                        signConfigModel = signConfigModelMapper.selectOne(signConfigModel);
                        if (signConfigModel != null) {
                            status = signConfigModel.getIs_status();
                        }
                        break;
                    case DictionaryConst.Plugin.SUBTRACTION:
                        SubtractionConfigModal subtractionConfigModal = new SubtractionConfigModal();
                        subtractionConfigModal.setStore_id(storeId);
                        subtractionConfigModal = subtractionConfigModalMapper.selectOne(subtractionConfigModal);
                        if (subtractionConfigModal != null) {
                            status = subtractionConfigModal.getIs_subtraction();
                        }
                        break;
                    case DictionaryConst.Plugin.DISTRIBUTION:
                        //分销插件是否开启
                        DistributionConfigModel distributionConfigModel = new DistributionConfigModel();
                        distributionConfigModel.setStore_id(storeId);
                        distributionConfigModel = distributionConfigModelMapper.selectOne(distributionConfigModel);
                        if (distributionConfigModel != null) {
                            status = distributionConfigModel.getStatus();
                        }
                        break;
                    case DictionaryConst.Plugin.GOGROUP:
                        //禅道 48292
                        GroupOrderConfigModel groupOrderConfig = new GroupOrderConfigModel();
                        groupOrderConfig.setStore_id(storeId);
                        groupOrderConfig = groupOrderConfigModelMapper.selectOne(groupOrderConfig);
                        if (groupOrderConfig != null) {
                            status = groupOrderConfig.getIsOpen();
                        }
                        break;
                    case DictionaryConst.Plugin.SECONDS:
                        zyMchId = customerModelMapper.getStoreMchId(storeId);
                        SecondsConfigModel secondsConfigModel = new SecondsConfigModel();
                        secondsConfigModel.setStore_id(storeId);
                        secondsConfigModel.setMch_id(zyMchId);
                        secondsConfigModel = secondsConfigModelMapper.selectOne(secondsConfigModel);
                        if (secondsConfigModel != null && secondsConfigModel.getIs_open().equals(DictionaryConst.WhetherMaven.WHETHER_OK)) {
                            status = 1;
                        }
                        break;
                    case DictionaryConst.Plugin.PRESELL:
                        PreSellConfigModel preSellConfigModel = new PreSellConfigModel();
                        preSellConfigModel.setStore_id(storeId);
                        preSellConfigModel = preSellConfigModelMapper.selectOne(preSellConfigModel);
                        if (preSellConfigModel != null) {
                            status = preSellConfigModel.getIs_open();
                        }
                        break;
                    case DictionaryConst.Plugin.AUCTION:
                        AuctionConfigModel auctionConfigModel = new AuctionConfigModel();
                        auctionConfigModel.setStore_id(storeId);
                        auctionConfigModel = auctionConfigModelMapper.selectOne(auctionConfigModel);
                        if (auctionConfigModel != null) {
                            status = auctionConfigModel.getIs_open();
                        }
                        break;
                    case DictionaryConst.Plugin.COUPON:
                        //首先看平台是否开启了优惠券,如果关闭了其它店铺都跟着关闭
                        CouponConfigModel couponConfigModel = new CouponConfigModel();
                        couponConfigModel.setStore_id(storeId);
                        couponConfigModel.setMch_id(0);
                        couponConfigModel = couponConfigModelMapper.selectOne(couponConfigModel);
                        if (couponConfigModel != null && DictionaryConst.WhetherMaven.WHETHER_OK == couponConfigModel.getIs_status()) {
                            status = 1;
                        }
                        break;
                    case DictionaryConst.Plugin.INTEGRAL:
                        //积分商城
                        zyMchId = customerModelMapper.getStoreMchId(storeId);
                        IntegralConfigModel integralConfigModel = new IntegralConfigModel();
                        integralConfigModel.setStore_id(storeId);
                        integralConfigModel.setMch_id(zyMchId);
                        integralConfigModel = integralConfigModelMapper.selectOne(integralConfigModel);
                        if (integralConfigModel != null){
                            status = integralConfigModel.getStatus();
                        }
                        break;
                    case DictionaryConst.Plugin.BARGAIN:
                        BargainConfigModel bargainConfigModel = new BargainConfigModel();
                        bargainConfigModel.setStore_id(storeId);
                        bargainConfigModel = bargainConfigModelMapper.selectOne(bargainConfigModel);
                        if (bargainConfigModel != null) {
                            status = bargainConfigModel.getStatus();
                        }
                        break;
                    case DictionaryConst.Plugin.WALLET:
                        //钱包
                        ConfigModel configModel = new ConfigModel();
                        configModel.setStore_id(storeId);
                        configModel = configModelMapper.selectOne(configModel);
                        if (configModel != null) {
                            //钱包没有隐藏
                            if (configModel.getHide_your_wallet() == 0) {
                                PaymentModel paymentModel = new PaymentModel();
                                paymentModel.setClass_name(DictionaryConst.OrderPayType.ORDERPAYTYPE_WALLET_PAY);
                                paymentModel = paymentModelMapper.selectOne(paymentModel);
                                if (paymentModel == null) {
                                    break;
                                }
                                //钱包没有被禁用
                                PaymentConfigModel paymentConfigModel = new PaymentConfigModel();
                                paymentConfigModel.setStore_id(storeId);
                                paymentConfigModel.setPid(paymentModel.getId());
                                paymentConfigModel = paymentConfigModelMapper.selectOne(paymentConfigModel);
                                if (paymentConfigModel == null) {
                                    break;
                                }
                                if (paymentConfigModel.getStatus() == 1) {
                                    status = paymentConfigModel.getStatus();
                                }
                            }
                        }
                        break;
                    case DictionaryConst.Plugin.MCH:
                        MchConfigModel mchConfigModel = new MchConfigModel();
                        mchConfigModel.setStore_id(storeId);
                        mchConfigModel.setMch_id(mchId);
                        mchConfigModel = mchConfigModelMapper.selectOne(mchConfigModel);
                        if (mchConfigModel != null) {
                            status = mchConfigModel.getIs_display();
                        }
                        break;
                    case DictionaryConst.Plugin.DIY:
                        //diy如果启用则判断是否应用了diy模板
                        DiyModel diyModel = new DiyModel();
                        diyModel.setStore_id(storeId);
                        diyModel.setStatus(DictionaryConst.WhetherMaven.WHETHER_OK);
                        int count = diyModelMapper.selectCount(diyModel);
                        if (count > 0) {
                            status = DictionaryConst.WhetherMaven.WHETHER_OK;
                        }
                        break;
                    case DictionaryConst.Plugin.MEMBER:
                        Map<String, Object> config = memberConfigMapper.getConfig(storeId);
                        Integer isOpen = MapUtils.getInteger(config, "is_open");
                        if (isOpen != null && isOpen > 0) {
                            status = isOpen;
                        }
                        break;
                    default:
                        status = 1;
                        break;
                }
            }
            if (pluginMap != null) {
                pluginMap.put(pluginCode, status);
            }
            return status == 1;
        } catch (LaiKeAPIException l) {
            throw l;
        } catch (Exception e) {
            logger.error("验证插件是否开启 异常", e);
            throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_WLYC, "网络异常", "frontPlugin");
        }
    }

    @Autowired
    private ActivityModelMapper activityModelMapper;

    @Override
    public boolean activityPlugin(int storeId, String pluginCode) throws LaiKeAPIException {
        try {
            boolean switchFlag = false;
            if (this.frontPlugin(storeId, null, pluginCode, null)) {
                int pluginType;
                switch (pluginCode.toLowerCase()) {
                    case DictionaryConst.Plugin.INTEGRAL:
                        pluginType = DictionaryConst.GoodsActive.GOODSACTIVE_INTEGRAL;
                        break;
                    case DictionaryConst.Plugin.SECONDS:
                        pluginType = DictionaryConst.GoodsActive.GOODSACTIVE_SECONDS;
                        break;
                    default:
                        return true;
                }
                switchFlag = activityModelMapper.pluginSwitch(storeId, pluginType) > 0;
            }
            return switchFlag;
        } catch (LaiKeAPIException l) {
            throw l;
        } catch (Exception e) {
            logger.error("插件活动是否开启 异常", e);
            throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_WLYC, "网络异常", "activityPlugin");
        }
    }

    @Override
    public Map<String, Object> commodityInformation(int storeId, int mchId) throws LaiKeAPIException {
        Map<String, Object> resultMap = new HashMap<>(16);
        try {
            //在售商品数量
            int goodsNum;
            //已售数量
            int quantitySold;
            //收藏数量
            int collectionNum;

            Map<String, Object> parmaMap = new HashMap<>(16);

            List<Integer> goodsStatus = new ArrayList<>();
            //获取商户产品配置
            ProductConfigModel productConfigModel = new ProductConfigModel();
            productConfigModel.setStore_id(storeId);
            productConfigModel = productConfigModelMapper.selectOne(productConfigModel);
            //已上架
            goodsStatus.add(DictionaryConst.GoodsStatus.NEW_GROUNDING);
            if (productConfigModel != null && productConfigModel.getIs_open() != 0) {
                //已下架
                goodsStatus.add(DictionaryConst.GoodsStatus.OFFLINE_GROUNDING);
            }
            //获取匹配到的商品
            parmaMap.put("store_id", storeId);
            parmaMap.put("mch_id", mchId);
            parmaMap.put("mch_status", DictionaryConst.GoodsMchExameStatus.EXAME_PASS_STATUS);
            parmaMap.put("GoodsStatus", goodsStatus);
            //在售商品数量
            goodsNum = productListModelMapper.countProductListDynamic(parmaMap);
            //获取商品销售信息
            quantitySold = productListModelMapper.sumDynamic(parmaMap).intValue();

            //获取收藏数量
            UserCollectionModel userCollectionModel = new UserCollectionModel();
            userCollectionModel.setStore_id(storeId);
            userCollectionModel.setMch_id(mchId);
            collectionNum = userCollectionModelMapper.selectCount(userCollectionModel);

            resultMap.put("quantity_on_sale", goodsNum);
            resultMap.put("quantity_sold", quantitySold);
            resultMap.put("collection_num", collectionNum);
        } catch (LaiKeAPIException l) {
            throw l;
        } catch (Exception e) {
            logger.error("获取商品信息异常", e);
            throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_WLYC, "网络异常", "commodityInformation");
        }
        return resultMap;
    }

    @Override
    public String getWeiXinToken(int storeId) throws LaiKeAPIException {
        String token = "";
        try {
            ConfigModel configModel = new ConfigModel();
            configModel.setStore_id(storeId);
            configModel = configModelMapper.selectOne(configModel);
            if (configModel != null) {
                token = jssdk.getAccessToken(configModel.getAppid(), configModel.getAppsecret());
            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.info("获取微信token 异常:" + e.getMessage());
            throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_WLYC, "网络异常", "getWeiXinToken");
        }
        return token;
    }

    @Override
    public boolean addAdminRecord(int storeId, String userId, String text, int type, int source, int mchId) throws LaiKeAPIException {
        try {
            AdminRecordModel adminRecordModel = new AdminRecordModel();
            adminRecordModel.setStore_id(storeId);
            adminRecordModel.setAdmin_name(userId);
            adminRecordModel.setEvent(text);
            adminRecordModel.setType(type);
            adminRecordModel.setAdd_date(new Date());
            adminRecordModel.setSource(source);
            adminRecordModel.setMchId(mchId);
            int count = adminRecordModelMapper.insertSelective(adminRecordModel);
            if (count > 0) {
                return true;
            }
        } catch (Exception e) {
            logger.info("添加操作记录 异常:", e);
        }
        return false;
    }

    @Override
    public boolean addAdminRecord(int storeId, String userId, String text, int type, int source, int mchId, int adminId) throws LaiKeAPIException {
        try {
            AdminRecordModel adminRecordModel = new AdminRecordModel();
            adminRecordModel.setStore_id(storeId);
            adminRecordModel.setAdmin_name(userId);
            adminRecordModel.setEvent(text);
            adminRecordModel.setType(type);
            adminRecordModel.setAdd_date(new Date());
            adminRecordModel.setSource(source);
            adminRecordModel.setMchId(mchId);
            adminRecordModel.setOperator_id(adminId);
            int count = adminRecordModelMapper.insertSelective(adminRecordModel);
            if (count > 0) {
                return true;
            }
        } catch (Exception e) {
            logger.info("添加操作记录 异常:", e);
        }
        return false;
    }

    @Override
    public boolean addAdminRecord(int storeId, String text, int type, String token) throws LaiKeAPIException {

        try{

            int count = 0;
            AdminRecordModel adminRecordModel = new AdminRecordModel();
            adminRecordModel.setStore_id(storeId);
            adminRecordModel.setEvent(text);
            adminRecordModel.setType(type);
            adminRecordModel.setAdd_date(new Date());
            //判读是哪个平台
            // 管理后台
            Object cacheValue = redisUtil.get(com.laiketui.core.lktconst.GloabConst.RedisHeaderKey.LOGIN_ACCESS_MANAGE_TOKEN + token);
            AdminModel adminModel = new AdminModel();
            User user = new User();
            if(cacheValue!=null){
                adminModel = JSON.parseObject(cacheValue.toString(),AdminModel.class);
                adminRecordModel.setAdmin_name(adminModel.getName());
                adminRecordModel.setSource(AdminRecordModel.Source.PC_PLATFORM);
                adminRecordModel.setMchId(-1);
                adminRecordModel.setOperator_id(adminModel.getId());
                count = adminRecordModelMapper.insertSelective(adminRecordModel);
                if (count > 0) {
                    return true;
                }
            }else if (cacheValue == null) {
                //店铺后台
                cacheValue = redisUtil.get(com.laiketui.core.lktconst.GloabConst.RedisHeaderKey.LOGIN_ACCESS_MCH_TOKEN + token);
                if (cacheValue != null) {
                    user = JSON.parseObject(cacheValue.toString(), User.class);
                    adminRecordModel.setAdmin_name(user.getUser_id());
                    adminRecordModel.setSource(AdminRecordModel.Source.PC_SHOP);
                    adminRecordModel.setMchId(user.getMchId());
                    adminRecordModel.setOperator_id(user.getId());
                    count = adminRecordModelMapper.insertSelective(adminRecordModel);
                    if (count > 0) {
                        return true;
                    }
                }
            }else if (cacheValue == null){
                return true;
            }
        }catch (Exception e){
            logger.error("添加记录异常 异常", e);
            throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_WLYC, "网络异常");
        }
        return false;
    }

    @Autowired
    private AdminRecordModelMapper adminRecordModelMapper;

    @Autowired
    private RoleMenuModelMapper roleMenuModelMapper;

    @Autowired
    private CommentsModelMapper commentsModelMapper;

    @Autowired
    private CommentsImgModelMapper commentsImgModelMapper;

    @Autowired
    private ReplyCommentsModelMapper replyCommentsModelMapper;

    @Autowired
    private ProductConfigModelMapper productConfigModelMapper;

    @Autowired
    private UserCollectionModelMapper userCollectionModelMapper;

    @Autowired
    private PluginsModelMapper pluginsModelMapper;

    @Autowired
    private SignConfigModelMapper signConfigModelMapper;

    @Autowired
    private SubtractionConfigModalMapper subtractionConfigModalMapper;

    @Autowired
    private DistributionConfigModelMapper distributionConfigModelMapper;

    @Autowired
    private GroupConfigModelMapper groupConfigModelMapper;

    @Autowired
    private PreSellConfigModelMapper preSellConfigModelMapper;

    @Autowired
    private AuctionConfigModelMapper auctionConfigModelMapper;

    @Autowired
    private CouponConfigModelMapper couponConfigModelMapper;

    @Autowired
    private BargainConfigModelMapper bargainConfigModelMapper;

    @Autowired
    private ConfigModelMapper configModelMapper;

    @Autowired
    private PaymentModelMapper paymentModelMapper;

    @Autowired
    private PaymentConfigModelMapper paymentConfigModelMapper;

    @Autowired
    private MchConfigModelMapper mchConfigModelMapper;

    @Autowired
    private IntegralConfigModelMapper integralConfigModelMapper;

    @Autowired
    private SecondsConfigModelMapper secondsConfigModelMapper;

    @Autowired
    private SecondsLabelModelMapper secondsLabelModelMapper;

    @Autowired
    private MemberConfigMapper memberConfigMapper;

    @Autowired
    private Jssdk jssdk;
}

